import json
import time
from decimal import Decimal

from django.core.cache import cache
from django.shortcuts import render
from django_redis import get_redis_connection
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView

from courses.models import Course

import logging

# Create your views here.

logger = logging.getLogger('django')


class CartView(APIView):
    """
    添加购物车
    """

    permission_classes = []

    def post(self, request):
        """
        添加购物车
        """
        try:
            # 1:获取参数
            course_id = request.data.get('course_id')
            quantity = int(request.data.get('quantity', 1))

            # 检查用户是否登录
            if not request.user.is_authenticated:
                return Response({
                    "code": 2,  # 使用特殊状态2 表示未登录
                    "message": "用户未登录"
                })

            user_id = request.user.id

            # 2:校验参数
            if not course_id:
                return Response({
                    'code': 0,
                    'message': '课程ID不能为空'
                })

            # 3:业务校验,查询课程
            try:
                course = Course.objects.get(id=course_id, is_deleted=False)
            except Course.DoesNotExist:
                return Response({
                    'code': 0,
                    'message': '课程不存在'
                })

            # 判断课程是否上架
            if course.status != 1:
                return Response({
                    'code': 0,
                    'message': '课程未上架'
                })

            if course.course_type == 1:
                return Response({
                    "code": 0,
                    "message": "课程为免费课程,不能添加购物车"}
                )
            # h获取redis连接
            redis_conn = get_redis_connection('default')
            # 购物车的 hash KEY
            cart_key = f"code_env_space:cart:cartList:{user_id}"
            course_key = f"course_{course_id}"

            # 判断课程是否已经添加到购物车
            if redis_conn.hexists(cart_key, course_key):
                return Response({
                    "code": 0,
                    "message": "课程已在购物车中"}
                )

            # 将课程信息存入到redis  Hash
            course_data = {
                "name": course.name,
                "price": float(course.price),  # Decimal转化float
                "is_selected": 1,  # 默认选中
                "quantity": quantity
            }
            redis_conn.hset(
                cart_key,
                course_key,
                json.dumps(course_data)

            )

            return Response({
                "code": 1,
                "message": "添加购物车成功",
                "data": course_data}
            )

            # 更新Zset,用于记录添加顺序
            # order_key = f"code_env_space:cart:order:{user_id}"
            # redis_conn.zadd(order_key,f"{course_id}:{time.time()}")


        except Exception as e:
            logger.error(e)
            return Response({
                "code": 0, "message": "添加购物车失败"})


class CartListView(APIView):
    """
    购物车列表
    """

    permission_classes = []

    def get(self, request):
        try:
            if not request.user.is_authenticated:
                return Response({
                    "code": 2,
                    "message": "用户未登录"
                })
            user_id = request.user.id

            # h获取redis连接
            redis_conn = get_redis_connection('default')
            # 购物车的 hash KEY
            cart_key = f"code_env_space:cart:cartList:{user_id}"

            cart_data = redis_conn.hgetall(cart_key)
            if not cart_data:
                return Response({
                    "code": 0,
                    "message": "购物车为空"
                })

            logger.info(cart_data)
            logger.info(type(cart_data))

            cart_list = []
            total_price = Decimal('0.00')
            for course_id, course_info in cart_data.items():
                courseId = course_id.decode()
                logger.info(courseId)
                logger.info(type(courseId))
                courseInfo = course_info.decode()
                logger.info(courseInfo)
                logger.info(type(courseInfo))
                course_info = json.loads(courseInfo)
                logger.info(course_info)
                logger.info(type(course_info))
                # course_34
                logger.info(courseId)
                logger.info(courseId.split("_"))
                c_list = courseId.split("_")

                logger.info(c_list[1])
                # logger.info(courseId.split("_"))
                # logger.info(courseId.split("_")[1])
                #
                # c_id = int(courseId.split("_")[1])
                courseId = c_list[1]
                course = Course.objects.get(id=courseId)
                total_price += Decimal(str(course.price))

                my_course_info = {
                    'id': courseId,
                    'name': course.name,
                    'price': float(course.price),
                    'quantity': course_info['quantity'],
                    'is_selected': course_info['is_selected'],
                    "course_img": course.course_img,

                }
                cart_list.append(my_course_info)

            return Response({
                "code": 1,
                "message": "获取购物车列表成功",
                "data": {
                    "cart_list": cart_list,
                    "total_price": float(total_price)
                }
            })

        except Exception as e:
            logger.error(e)
            return Response({
                "code": 0,
                "message": "获取购物车列表失败"
            })


class CartDelView(APIView):
    """
    删除购物车
    单个
    {
    “course_ids”:1

    }

    批量删除
      {
    “course_ids”:[1,2,3]

    }

    """

    permission_classes = []

    def post(self, request):
        try:
            if not request.user.is_authenticated:
                return Response({
                    "code": 0,
                    "message": "用户未登录"
                })

            course_ids = request.data.get("course_ids")
            if not course_ids:
                return Response({
                    "code": 0,
                    "message": "请选择要删除的课程"
                })

            if isinstance(course_ids, int):
                course_ids = [course_ids]
            elif not isinstance(course_ids, list):
                return Response({
                    "code": 0,
                    "message": "参数格式错误"
                })

            user_id = request.user.id

            redis_conn = get_redis_connection('default')

            # 购物车的 hash KEY
            cart_key = f"code_env_space:cart:cartList:{user_id}"

            # course_key = f"course_{course_id}"

            deleted_count = 0
            for course_id in course_ids:
                course_key = f"course_{course_id}"
                # 检车课程是否在这个用户 的购物车中
                if redis_conn.hexists(cart_key, course_key):
                    redis_conn.hdel(cart_key, course_key)
                    deleted_count += 1

            logger.info(f"用户{user_id}从购物车中删除了{deleted_count}门课程")

            return Response({
                "code": 1,
                "message": "删除购物车成功",
                "data": {
                    "deleted_count": deleted_count
                }
            })


        except Exception as e:
            logger.error(e)
            return Response({
                "code": 0,
                "message": f"删除购物车失败:{str(e)}"
            })


class CartSelectAllView(APIView):
    """
    全选购物车
    """

    permission_classes = []

    def post(self, request):
        try:
            if not request.user.is_authenticated:
                return Response({
                    "code": 0,
                    "message": "用户未登录"
                })

            user_id = request.user.id
            # 获取选中状态
            selected = request.data.get("selected")

            logger.info(f"用户选中的状态:[{selected}]")

            if selected is None:
                logger.info(f"用户选中的状态:[{selected}]")
                return Response({
                    "code": 0,
                    "message": "请提供选中的状态"
                })

            selected = int(selected)
            if selected not in [0, 1]:
                return Response({
                    "code": 0,
                    "message": "选中状态必须是0或者1"
                })

            redis_conn = get_redis_connection('default')
            # 购物车的 hash KEY
            cart_key = f"code_env_space:cart:cartList:{user_id}"

            # 获取购物车中所有的课程
            cart_data = redis_conn.hgetall(cart_key)
            logger.info(f"用户:[{user_id},购物车数据:[{cart_data}]]")
            if not cart_data:
                return Response({
                    "code": 0,
                    "message": "购物车为空"
                }

                )
            updated_count = 0
            for course_key, course_data_bytes in cart_data.items():
                # 把购物车里面的课程数据(字节)--》json字符串---〉字典
                course_data = json.loads(course_data_bytes.decode())
                if course_data["is_selected"] != selected:
                    course_data["is_selected"] = selected
                    redis_conn.hset(cart_key, course_key, json.dumps(course_data))
                    updated_count += 1

            action = "全选" if selected == 1 else "取消全选"
            logger.info(f"用户:[{user_id},{action}购物车数据:[{cart_data}]],更新了{updated_count}个课程")
            return Response({
                "code": 1,
                "message": f"{action}购物车成功",
                "data": {
                    "updated_count": updated_count
                }
            })

        except Exception as e:
            logger.error(e)
            return Response({
                "code": 0,
                "message": f"{action}购物车失败:{str(e)}"
            })


class CartToggleSelectView(APIView):
    permission_classes = []

    def post(self, request):
        try:
            if not request.user.is_authenticated:
                return Response({
                    "code": 0,
                    "message": "用户未登录"
                })

            course_ids = request.data.get('course_ids')

            if not course_ids:
                return Response({
                    "code": 0,
                    "message": "请选择要切换的课程"
                })

            if isinstance(course_ids, int):
                course_ids = [course_ids]
            elif not isinstance(course_ids, list):
                return Response({
                    "code": 0,
                    "message": "参数格式错误"
                })

            user_id = request.user.id

            redis_conn = get_redis_connection('default')
            # 购物车的 hash KEY
            cart_key = f"code_env_space:cart:cartList:{user_id}"
            updated_count = 0
            updated_course = []
            for course_id in course_ids:
                course_key = f"course_{course_id}"
                if redis_conn.hexists(cart_key, course_key):
                    course_data = json.loads(redis_conn.hget(cart_key, course_key).decode())
                    course_data['is_selected'] = 1 if course_data['is_selected'] == 0 else 0
                    redis_conn.hset(cart_key, course_key, json.dumps(course_data))
                    updated_count += 1
                    updated_course.append({
                        'course_id': course_id,
                        "is_selected": course_data['is_selected']
                    })

            return Response({
                "code": 1,
                "message": "反选成功",
                "data": {
                    "updated_count": updated_count,
                    "updated_course": updated_course
                }
            })

        except Exception as e:
            logger.error(e)
            return Response({
                "code": 0,
                "message": f"反选失败:{str(e)}"
            })
